import { defineStore } from 'pinia'
import { setTheme, type ThemeMode } from '@/utils/ToolFunctions/setTheme'
import { useDataCountStore } from './dataCount'

interface UserInfo {
  name: string
  avatar: string
  token: string
  uid: string
}
interface UserStore {
  create: number
  done: number
  theme?: ThemeMode
  token?: string
  avatar?: string
  name?: string
  uid?: string
}

const useUserStore = defineStore('old-user', {
  state: (): UserStore => {
    return {
      create: 0,
      done: 0
    }
  },

  actions: {
    /** 设置深色模式 */
    setTheme(theme?: ThemeMode) {
      if (theme === undefined) theme = this.theme
      this.theme = setTheme(theme)
    },

    /** 记录创建新任务  */
    updataCreate(time: Date = new Date()) {
      useDataCountStore().updataCount(time)
      this.create++
    },

    /** 更新完成任务数 */
    updataDone(value: -1 | 1) {
      this.done += value
    },

    /** 设置用户信息 */
    setUserInfo(userInfo: UserInfo) {
      this.$patch((state) => {
        state.name = userInfo.name
        state.token = userInfo.token
        state.avatar = userInfo.avatar
        state.uid = userInfo.uid
      })
    },

    /** 清除用户信息 */
    logout() {
      localStorage.removeItem('token')
      this.$patch((state) => {
        state.name = undefined
        state.token = undefined
        state.avatar = undefined
        state.uid = undefined
      })
    }
  },

  persist: {
    key: 'user'
  }
})

export { useUserStore }
